package com.simba.server.task;

import java.io.File;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.simba.server.commands.impl.del.*;
import com.simba.server.components.CommandExecutor;
import org.apache.log4j.Logger;


import com.simba.common.log.LogUtil;
import com.simba.server.base.TimeUtil;

import com.simba.server.components.SortProtocolCreator;
import com.simba.server.components.SorterParams;
import com.simba.server.components.data.DeleteData;

public class DataClearTask extends Thread
{
	private final static Logger logger = Logger.getLogger(DataClearTask.class);
	private static final int REQUEST_INTERVAL = 30 * 1000;

	public DataClearTask()
	{
		this.setName("Data-Clear-Task");
	}

	public void doClearData()
	{
		this.doClearPacketOff(SorterParams.getInstance().getRestorePacketOffDays());
		this.doClearSlotPack(SorterParams.getInstance().getRestoreSlotPackDays());
		this.doClearPacketOn(SorterParams.getInstance().getRestorePacketOffDays());
		this.doClearPackageOffHistory(180);
		this.doClearPackageOffReport(2);
		this.doClearSlotPackHistory(180);
		this.doClearLogFiles(SorterParams.getInstance().getLogSaveDays());
	}

	@Override
	public void run()
	{
		while (!Thread.currentThread().isInterrupted())
		{
			try
			{
				this.deleteOverTimeSortData();
				Thread.sleep(DataClearTask.REQUEST_INTERVAL);
			}
			catch (Exception ex)
			{
				if (ex instanceof InterruptedException)
				{
					Thread.currentThread().interrupt();
				}
				LogUtil.LogError(DataClearTask.logger,
						"Catch an exception [" + ex.getMessage() + "]");
			}
		}
	}

	private void deleteOverTimeSortData()
	{
		try
		{
			Timestamp nowTime = SortProtocolCreator.getInstance().createCurrentTimeStamp();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time = nowTime.toString();
			Date date = format.parse(time);

			@SuppressWarnings("deprecation")
			int hour = date.getHours();
			int deleteDataTime = SorterParams.getInstance().getDeleteDataTime();
			if (hour == deleteDataTime)
			{
				this.doClearData();
			}
		}
		catch (ParseException ex)
		{
			LogUtil.LogError(DataClearTask.logger,
					"[deleteOverTimeSortData] : Catch an exception [" + ex.getMessage() + "]");
		}
	}

	private void doClearPackageOffHistory(int restoreDays)
	{
		DeleteData deleteData = TimeUtil.getDeleteTimestamp(restoreDays);

		CommandExecutor.executorSqlCommand(DelPackageOffHistoryCmd.NAME,deleteData,false);

		if (deleteData.getDelCount() > 0)
		{
			LogUtil.LogDebug(DataClearTask.logger,
					"Delete PackageOff History Data Count : [" + deleteData.getDelCount() + "]");
		}
	}

	private void doClearPackageOffReport(int restoreDays)
	{
		DeleteData deleteData = TimeUtil.getDeleteTimestamp(restoreDays);

		CommandExecutor.executorSqlCommand(DelPacketOffReportCmd.NAME,deleteData,false);

		if (deleteData.getDelCount() > 0)
		{
			LogUtil.LogDebug(DataClearTask.logger,
					"Delete PackageOff Report Data Count : [" + deleteData.getDelCount() + "]");
		}
	}

	private void doClearPacketOff(int restoreDays)
	{
		DeleteData deleteData = TimeUtil.getDeleteTimestamp(restoreDays);

		CommandExecutor.executorSqlCommand(DelPacketOffCmd.NAME,deleteData,false);

		if (deleteData.getDelCount() > 0)
		{
			LogUtil.LogDebug(DataClearTask.logger,
					"Delete Packet Off Data Count : [" + deleteData.getDelCount() + "]");
		}
	}

	private void doClearPacketOn(int restoreDays)
	{
		DeleteData deleteData = TimeUtil.getDeleteTimestamp(restoreDays);

		CommandExecutor.executorSqlCommand(DelPacketOnCmd.NAME,deleteData,false);

		if (deleteData.getDelCount() > 0)
		{
			LogUtil.LogDebug(DataClearTask.logger,
					"Delete Packet On Data Count : [" + deleteData.getDelCount() + "]");
		}
	}









	private void doClearSlotPack(int restoreDays)
	{
		DeleteData deleteData = TimeUtil.getDeleteTimestamp(restoreDays);

		CommandExecutor.executorSqlCommand(DelSlotPackCmd.NAME,deleteData,false);

		if (deleteData.getDelCount() > 0)
		{
			LogUtil.LogDebug(DataClearTask.logger,
					"Delete Slot Pack Data Count : [" + deleteData.getDelCount() + "]");
		}
	}

	private void doClearSlotPackHistory(int restoreDays)
	{
		DeleteData deleteData = TimeUtil.getDeleteTimestamp(restoreDays);
		CommandExecutor.executorSqlCommand(DelSlotPackHistoryCmd.NAME,deleteData,false);

		if (deleteData.getDelCount() > 0)
		{
			LogUtil.LogDebug(DataClearTask.logger,
					"Delete Slot Pack History Data Count : [" + deleteData.getDelCount() + "]");
		}
	}

	private void doClearLogFiles(int restoreDays)
	{
		try
		{
			long restoreTime = restoreDays * 24 * 60L;

			File files = new File("logs");
			if (files.listFiles()==null)
			{
				return;
			}
			for (File file: files.listFiles())
			{
				if (file.isDirectory())
				{
					continue;
				}
				String fileName = file.getName();
				String[] items = fileName.split("\\.");
				if (items.length == 3)
				{
					String date = items[2]+" 00:00:00";
					String currentDate = TimeUtil.getTimeDateString("yyyy-MM-dd HH:mm:ss", new Date());
					long difference = TimeUtil.getTimeDifference(date, currentDate);
					if (difference>restoreTime)
					{
						file.delete();
					}

				}
			}
		}catch (Exception e)
		{
			LogUtil.LogError(DataClearTask.logger, "Delete Log File Error: "+ e.getMessage());
		}

	}
}
